
# 登陆、注册模块
import pymysql
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app)

auth_bp = Blueprint('auth', __name__, url_prefix='/auth')

# 注册成功则自动更新用户信息表
def insert_user_info(user_id):
    # 获取数据库
    db_pool = current_app.db_pool
    db_conn = g.db_conn
    db_cursor = g.db_cursor

    sql = "INSERT INTO user_info (user_id) VALUES (%s)"

    db_pool.execute_update(db_conn, sql, db_cursor, args=(user_id,))



@auth_bp.route('/login', methods=('GET', 'POST'))
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # 获取数据库
        db_pool = current_app.db_pool
        db_conn = g.db_conn
        db_cursor = g.db_cursor
        print(type(db_cursor))
        error = None
        if not username or not password:
            error = '用户名或密码为空'
        
        # 没有添加错误逻辑
        if not error:
            sql = 'select id, username from users where username = %s and user_password = %s'
            
            result = db_pool.execute_query(db_conn, sql, db_cursor, (username, password))
            if result:
                session.clear()
                session['user_id'] = result['id'] # 会存储在浏览器的cookie当中，下次登录，可以直接从cookie中获取
                g.is_login = True
                return redirect(url_for('user.myProfile'))

            else:
                error = '用户名或密码错误'
                flash(error)
    return render_template('auth/login.html')

@auth_bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        db_pool = current_app.db_pool
        db_conn = g.db_conn
        db_cursor = g.db_cursor

        error = None
        user_id = None
        if not username and not password:
            error = '用户名或密码为空'

        if not error: 
            sql = 'insert into users (username, user_password) values (%s, %s)'

            try:
                user_id = db_pool.execute_update(db_conn, sql, db_cursor, (username, password))

            except pymysql.Error as e:
                error = '用户名已存在'
                print(e)
            
        if error:
            flash(error)
        else:
            if user_id:
                insert_user_info(user_id)
                print('user_id: ', user_id)
            return redirect(url_for('auth.login'))
    
    return render_template('auth/register.html')
    
def init_app(app):
    @app.before_request
    def before_request():
        # 是否登录过
        if session.get('user_id') is None:
            return redirect(url_for('auth.login'))
        else:
            g.is_login = True
            g.user_id = session['user_id']

                                
